//
//  CWOAuthController.swift
//  CWWeibo06
//
//  Created by ycw on 2017/7/23.
//  Copyright © 2017年 xiaowei. All rights reserved.
//

import UIKit
import SVProgressHUD

let AppKey: String = "359376674"
let redirect_uri: String = "http://www.itcast.cn"
var code: String = ""

class CWOAuthController: CWVisibleController,UIWebViewDelegate {
    
    //第三方登录页面
    
    //https://api.weibo.com/oauth2/authorize?client_id=359376674&redirect_uri=http://www.itcast.cn&response_type=code
    
    //懒加载webView
    fileprivate lazy var webView: UIWebView = {
        
        let web = UIWebView()
        
        web.delegate = self
        
        web.loadRequest(URLRequest.init(url: URL(string: "https://api.weibo.com/oauth2/authorize?client_id=\(AppKey)&redirect_uri=\(redirect_uri)&response_type=code")!, cachePolicy: URLRequest.CachePolicy.reloadIgnoringLocalAndRemoteCacheData, timeoutInterval: 1))
        
        return web
        
    }()
    
    override func loadView() {
        
        view = webView
        
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        addNavigationItem()

        // Do any additional setup after loading the view.
    }
    
    //添加导航栏和左右侧按钮
    
    @objc private func addNavigationItem() {
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", target: self, action: #selector(clickLeftBarButton))
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "快速登录", target: self, action: #selector(clickRightBarButton))
        
    }

    //MARK:点击左侧按钮返回的方法
    @objc private func clickLeftBarButton() {
        
        dismiss(animated: true, completion: nil)
        
    }
    //MARK: 点击快速登录按钮的方法
    @objc private func clickRightBarButton() {
        
        webView.stringByEvaluatingJavaScript(from: "document.getElementById('userId').value = '13695515635';document.getElementById('passwd').value = '131752003';document.getElementById('passwd').focus();")
        
    }
    
    //MARK: - UIWebViewDelegate -
    //开始加载的时候
    func webViewDidStartLoad(_ webView: UIWebView) {
        
        SVProgressHUD.show()
        
    }
    //结束加载的时候
    func webViewDidFinishLoad(_ webView: UIWebView) {
        
        SVProgressHUD.dismiss()
    }
    //加载失败的时候
    func webView(_ webView: UIWebView, didFailLoadWithError error: Error) {
        
        //SVProgressHUD.showError(withStatus: "哎呀出错了")
        SVProgressHUD.dismiss()
    }
    
    //将要加载请求的时候调用
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        //判断是否以回调页面开头
        if request.url?.absoluteString.hasPrefix(redirect_uri) == true {
            
            //判断是否是code开头
            if let params: String = request.url?.query, params.hasPrefix("code=") {
                
                let code1: String = params.substring(from: "code=".endIndex)
                
                code = code1
                CWNetworkTool.sharedTools.requestAccessToken(callBack: { (responseObject, error) in
                    
                    if error != nil{
                        //print(error!)
                    }else{
                        
                        let accountModel: CWUserAccount = CWUserAccount(dict: responseObject as! [String:Any])
                        
                        CWUserAccountViewModel.userAccountViewModel.requestUserInfo(accountModel: accountModel, callBack: { (isSuccess) in
                            
                            if isSuccess {
                                //print("登录成功")
                                //切换根视图控制器
                                self.dismiss(animated: false, completion: {
                                    //代码执行到此说明控制器已经被释放
                                    NotificationCenter.default.post(name:                      NSNotification.Name(rawValue: SwitchRootViewControllerNotification), object: self)
                                 })
                                
                            }else{
                                //print("登录失败")
                            }
                            
                        })
                        
                    }
                    
                })
                
            }else {
                
                dismiss(animated: true, completion: nil)
            }
            
            
            return false
            
        }
        return true
    }
    
    
    

}


